<!--  -->
<template>
  <van-dialog :show="showModel" title="" :showConfirmButton="false" class="custom-model">
    <div class="title">用户登录</div>
    <CloseCircleOutlined @click="handleModelClose" />
    <input v-model="phone" type="text" placeholder="请输入移动手机号码" class="phone-input" />
    <div class="yzm">
      <input v-model="code" type="text" placeholder="请输入验证码" class="code-input" />
      <span @click="handleGetCode">{{ yzmText }}</span>
    </div>
    <van-button type="primary" loading-text="" class="login-btn" @click="handleYzmLogin"
      >登录</van-button
    >

    <van-button
      type="primary"
      loading-text="本机号码一键登录"
      class="login-code"
      @click="handleOnkeyLogin"
      >本机号码一键登录</van-button
    >
    <div class="tips">
      <p>3G/4G/5G环境下建议选择一键登录<br />Wi-Fi环境下请选择短信登录</p>
    </div>
  </van-dialog>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, ref } from 'vue'
import { CloseCircleOutlined } from '@ant-design/icons-vue'
import userApi from '@/api/mobile_user'
import commonApi from '@/api/common'
import config, { MODE } from '@/config'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { Toast } from 'vant'
import { useStore } from '@/store'
import { Storage } from '@/utils/Storage'
import { MOBILE_TOKEN, MOBILE_USER } from '@/store/mutation-types'

// https://segmentfault.com/q/1010000038774261/a-1020000038804110
export default defineComponent({
  components: {
    CloseCircleOutlined
  },
  props: {
    showModel: {
      default: false,
      type: Boolean
    },
    whiteFlag: {
      default: '',
      type: String
    },
    blackFlag: {
      default: '',
      type: String
    }
  },
  emits: ['update:showModel', 'blackWhiteTips'],
  setup(props, context) {
    const store = useStore()
    const router = useRouter()
    let toastRef: any = ref(null)
    const route = useRoute()
    const state = reactive({
      isLogin: store.getters['user/isLogin'],
      yzmText: '获取验证码',
      msgidKey: '',
      phone: MODE === 'dev' ? '13922997439' : '', //'13922992916',
      code: '',
      yzmLoading: false,
      yzmDisabled: false,
      getMsgidStatus: false,
      isClickOneKeyLogin: false,
      banLogin: false
    })
    function handleModelClose() {
      context.emit('update:showModel', false)
    }
    let t = ref<any>(null)
    const handleGetCode = async () => {
      if (!config.validatePhoneRule.test(state.phone)) {
        message.warning('请输入正确的手机号码')
        return
      }
      if (t.value) return
      state.yzmLoading = true
      let res = await commonApi.getYzm({ mobile: state.phone })
      console.log('%c 🍉 res: ', 'font-size:20px;background-color: #4b4b4b;color:#fff;', res)
      state.yzmLoading = false
      let count = 60
      if (res.retCode == 0) {
        state.yzmDisabled = true
        t.value = setInterval(() => {
          count--
          state.yzmText = count + '秒重新获取'
          if (count <= 0) {
            clearInterval(t.value)
            state.yzmLoading = false
            state.yzmDisabled = false
            state.yzmText = '重新获取'
            t.value = null
          }
        }, 1000)
      } else {
        message.warning(res.retMsg)
      }
    }
    const checkWhitelist = (phone) => {
      return new Promise(async (resolve, reject) => {
        let res = await commonApi.checkWhite({ mobile: phone })
        if (~~props.whiteFlag == 1 || ~~props.blackFlag == 1) {
          if (res.status == 1) {
            //在黑名单  或者不在白名单
            state.banLogin = true
            context.emit('blackWhiteTips')
            resolve(false)
          } else {
            //在白名单
            resolve(true)
          }
        }
      })
    }

    const handleOnkeyLogin = async () => {
      toastRef.value = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '登录中'
      })

      if (state.getMsgidStatus && !state.msgidKey) {
        //获取 Msgid 完 但是获取失败 重新获取
        onkeyLogin(true)
      } else if (state.msgidKey) {
        //获取msgidKey 成功
        userApi.onkeyLogin({ msgidKey: state.msgidKey }).then(async (res) => {
          console.log(
            '%c 🎂 onkeyLogin: ',
            'font-size:20px;background-color: #33A5FF;color:#fff;',
            res
          )
          toastRef.value.clear()
          if (res.token) {
            let cres = await checkWhitelist(res.mobile)
            if (!cres) return //不在白名单
            handleStroage(res.token, res.phone)
          } else {
            message.warning('登录失败')
          }
        })
      } else {
        //没有获取完  但是点击了一键登陆
        state.isClickOneKeyLogin = true
      }
    }
    onMounted(() => {
      if (state.isLogin) return
      onkeyLogin(false)
    })
    function handleStroage(token, userphone) {
      let userInfo = { token: token, phone: userphone }
      Storage.set(MOBILE_TOKEN, token, 30 * 60)
      Storage.set(MOBILE_USER, userInfo, 30 * 60)
      store.commit('user/setMobileToken', token)
      store.commit('user/setMobileInfo', userInfo)
      message.success('登录成功')
      handleModelClose()
    }
    const handleYzmLogin = async () => {
      let toast = Toast.loading({
        message: '登录中...',
        forbidClick: true
      })
      let cres = await checkWhitelist(state.phone)
      if (!cres) return //不在白名单
      userApi.yzmLogin({ phone: state.phone, smsCode: state.code }).then((res) => {
        toast.clear()
        if (res.token) {
          handleStroage(res.token, state.phone)
        } else {
          message.warning(res.retMsg)
        }
        console.log('%c 🍥 res: ', 'font-size:20px;background-color: #EA7E5C;color:#fff;', res)
      })
    }

    function onkeyLogin(status) {
      // @ts-ignore
      Login.login(
        (msgidkey) => {
          state.getMsgidStatus = true
          state.msgidKey = msgidkey
          if (status || state.isClickOneKeyLogin) {
            handleOnkeyLogin()
          }

          console.log('获取msgidkey成功', msgidkey)
        },
        () => {
          state.getMsgidStatus = true
          if (toastRef.value) {
            toastRef.value.clear()
          }
          if (status || state.isClickOneKeyLogin) {
            message.warning('获取手机号失败，请打开移动网络，刷新页面重新尝试')
          }
          console.log('获取msgidkey失败')
        }
      )
    }
    return { handleModelClose, handleOnkeyLogin, ...toRefs(state), handleGetCode, handleYzmLogin }
  }
})
</script>
<style lang="scss">
.custom-model {
  padding: 32px 24px;

  .van-button {
    display: block;
    width: 272px;
    height: 40px;
    margin: 14px 0;
    background: #f1442f;
    border-radius: 20px;
  }

  p {
    font-size: 13px;
    color: rgba(0, 0, 0, 0.5);
    text-align: center;
  }

  .login-btn {
    font-size: 15px;
    letter-spacing: 8px;
    border: none;
  }

  .login-code {
    color: #f1442f;
    background: #fff;
    border: 1px solid #f1442f;
    border-radius: 20px;
  }

  .yzm {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .code-input {
      width: 157px;
    }

    span {
      width: 105px;
      height: 40px;
      font-size: 15px;
      line-height: 40px;
      color: #f1442f;
      text-align: center;
      border: 1px solid #f1442f;
      border-radius: 20px;
    }
  }

  .anticon-close-circle {
    position: absolute;
    top: 14px;
    right: 14px;
    width: 20px;
    height: 20px;
    line-height: 20px;
    color: #b3b3b3;
    text-align: center;
  }

  .phone-input {
    width: 100%;
    margin-bottom: 14px;
  }

  .title {
    margin-bottom: 24px;
    font-size: 17px;
    font-weight: 500;
    color: #000;
    text-align: center;
  }

  input {
    display: block;
    height: 40px;
    padding: 10px 17px;
    background: rgba(0, 0, 0, 0.1);
    border: none;
    border-radius: 20px;
    outline: none;
    box-sizing: border-box;

    &::placeholder {
      color: rgba(0, 0, 0, 0.5);
    }
  }
}
</style>
